package com.example.cameralib;

import android.graphics.Bitmap;
import android.media.FaceDetector;
import android.util.Log;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FaceDetect {
    private static final String TAG = "FaceDetect";
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private FaceDetect.FaceDetectCallBack callBack;

    private Boolean isRunning = false;

    private FaceDetector mFaceDetector;
    private FaceDetector.Face[] mFace;

    public void setCallBack(FaceDetect.FaceDetectCallBack callBack) {
        this.callBack = callBack;
    }

    interface FaceDetectCallBack {
        void face(FaceDetector.Face[] mFace, Bitmap bitmap);
    }

    public boolean detect(Bitmap bitmap) {
        synchronized (isRunning) {
            if (!isRunning) {
                executorService.execute(new FaceCapturedRunnable(bitmap));
                return true;
            }
        }
        return false;
    }

    public void release() {
        try {
            callBack = null;
            executorService.shutdownNow();
            executorService = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class FaceCapturedRunnable implements Runnable {
        private Bitmap newBitmap;

        public FaceCapturedRunnable(Bitmap captureBitmap) {
            this.newBitmap = captureBitmap;
        }

        @Override
        public void run() {
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(newBitmap, 160, 160, true);
            Bitmap captureBitmap = scaledBitmap.copy(Bitmap.Config.RGB_565, false);
            scaledBitmap.recycle();
            try {
                isRunning = true;
//                long time = System.currentTimeMillis();
                if (mFaceDetector == null)
                    mFaceDetector = new FaceDetector(captureBitmap.getWidth(), captureBitmap.getHeight(), 1);
                if (mFace == null)
                    mFace = new FaceDetector.Face[1];
                int detectedFaceNum = mFaceDetector.findFaces(captureBitmap, mFace);
                if (detectedFaceNum > 0 && callBack != null) {
                    callBack.face(mFace, newBitmap);
                } else if (callBack != null) {
                    callBack.face(null, newBitmap);
                }
                isRunning = true;
//                Log.i(TAG, "run: " + (System.currentTimeMillis() - time));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                captureBitmap.recycle();
                isRunning = false;
            }
        }
    }
}

